// 几个数据库的连接

use std::fmt::Debug;

use crate::settings::APP_SETTINGS;
use anyhow::{Context, Result};
use bb8::{Pool, PooledConnection};
use bb8_postgres::PostgresConnectionManager;
use log::info;
use mongodb::bson::oid::ObjectId;
use tokio_postgres::NoTls;

use mongodb::{options::ClientOptions, Client};
use mongodb::bson::{doc, Document};
use super::song::SongMetaInfo;

pub struct DBPool {
    pg_pool: Pool<PostgresConnectionManager<NoTls>>, // postgres
                                                     // minio
    mongo_cli: Client                                // mongo
}

pub async fn model_state() -> Result<DBPool> {
    let settings = APP_SETTINGS.lock().unwrap();

    // postgres
    let manager = PostgresConnectionManager::new_from_stringlike(
        format!(
            "host={} port={} user={} password={}",
            settings.pg_host, settings.pg_port, settings.pg_user, settings.pg_password
        ),
        NoTls,
    )
    .with_context(|| "new pg manager failed")?;

    let pool = Pool::builder().build(manager).await.with_context(|| "")?;
    // let p = pool.clone();
    // let conn = p.get().await?;
    // let row = conn.query("select version()", &[]).await?;
    // let ver:& str = row.get(0).unwrap().get(0);
    // info!("version:{}", ver.to_string());
    
    // Parse a connection string into an options struct.
    let mut client_options = ClientOptions::parse(format!("mongodb://{}:{}@{}:{}", settings.mg_user, settings.mg_password, settings.mg_host,settings.mg_port)).await.context("parse mongo url")?;
    
    // Manually set an option.
    client_options.app_name = Some("MusicmeCloud".to_string());

    // Get a handle to the deployment.
    let client = Client::with_options(client_options)?;

    let db = client.database("mg_musicme");
    let coll = db.collection::<SongMetaInfo>("song_meta");
    // ObjectId::new().to_string();
    let songs = vec![
        SongMetaInfo {
            id: ObjectId::new().to_string(),
            title: "abc".to_string(),
        }
    ];
    coll.insert_many(songs, None).await?;
    // List the names of the databases in that deployment.
// for db_name in client.list_database_names(None, None).await? {
//     println!("{}", db_name);
// }

    // minio

    Ok(DBPool { pg_pool: pool, mongo_cli: client})
}
